<template>
  <Modal class="select-company-model" v-model="modal" width='800' :title="title">
    <div class="h400 scroll">
       <Table :draggable="true" @on-drag-drop='onDragDrop' :data="list.data" :columns="list.columns"></Table>
    </div>
    <div slot="footer">
        <Button @click="closeModal" size="large" type="text">取消</Button>
        <Button @click="onSave" type="primary" size="large">确认</Button>
    </div>
    <Loader :status="status" @refresh="getData"></Loader>
  </Modal>
</template>
<script>
import { mapGetters } from 'vuex';
import { getOriginData } from "@/util";
export default {
  components: {
  },
  computed: {
    ...mapGetters(['currentDepartment']),
  },
  data() {
    return {
      modal: false,
      status: 'pass',
      title: '经销商排序',
      sortParams: {},
      list: {
        currentPage: 1,
        pageSize: 9999,
        columns: [
          {
            title: '经销商名-签约品牌',
            key: 'name',
            align: 'left',
          }, {
            title: '所属部门',
            key: 'departmentName',
            align: 'left',
          }
        ],
        data: [],
      }
    }
  },
  methods: {
    getData() {
      const { id, level } = this.currentDepartment
      if (!id || level != 3) return
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        id
      };
      this.list.status = "loading";
      this.$jsonPost(`/department/queryDistributorContracts/${id}`, param).then(data => {
        this.list.data = data.records || [];
        this.list.status = "pass";
      })
      .catch(() => {
        this.list.status = "error";
      });
    },
    onDragDrop(index1, index2) {
      let data = getOriginData(this.list.data)
      let temp = data[index2]
      data[index2] = data[index1]
      data[index1] = temp
      this.sortParams = {}
      this.list.data = data.map((item, idx) => {
        item.sort = idx+1
        this.sortParams[item.id] = item.sort
        return item
      })
    },
    onSave() {
      this.list.status = "loading"
      this.$jsonPost(`/department/changeDistributorOrder`, this.sortParams).then(data => {
        this.$Message.info('排序成功')
        this.$emit('sortSuccess')
        this.closeModal();
        this.list.status = "pass";
      })
      .catch(() => {
        this.list.status = "error";
      });
      
    },
    openModal() {
      this.modal = true;
      this.getData()
    },
    closeModal() {
      this.modal = false;
    },
  },
}
</script>
